package com.kira.scaffoldmvc.Dubbo;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.kira.scaffoldmvc.Dubbo.Compression.Factory.CompressionFactory;
import com.kira.scaffoldmvc.Dubbo.Compression.Strategy.CompressionStrategy;
import com.kira.scaffoldmvc.POJO.Result;
import org.apache.dubbo.config.annotation.Reference; // 正确
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.net.http.HttpClient;
import java.text.NumberFormat;
import java.util.Map;

@Slf4j
@Service
public class DesensitizationApiService {

    // Dubbo远程服务引用
    @Qualifier("desensitizationService")
    private IDesensitizationService desensitizationService;

    // 数据传输客户端
    private HttpUtil transferClient = new HttpUtil();

    // 开关配置
    @Resource
    private SwitchConfig switchConfig;

    // MongoDB客户端
    @Resource
    private MongoClient mongoClient;

    // 注入注入压缩算法工厂
    @Resource
    private CompressionFactory compressionFactory;

    /**
     * 查询历史脱敏分析结果
     */
    public Result composeAnalyzeHistory(Map<String, Object> condtion) {
        try {
            Result result = desensitizationService.composeAnalyzeHistory(condtion);
            return result;
        } catch (Exception e) {
            log.error("数据脱敏+识别异常，condtion = {}", condtion, e);
        }
        return Result.error("");
    }

    /**
     * 组合式敏感数据识别分析（核心方法）
     */
    public Result composeAnalyze(Map<String, Object> condtion) {
        String id = null;
        String retId = null;
        Result result = null;
        Result darResult = null;
        String finalResult = null;

        try {
            Boolean transferReview = switchConfig.isOpen();
            long t1 = System.currentTimeMillis(), t2 = t1, t3 = t1;

            String conditionStr = JSONUtil.toJsonStr(condtion);
            byte[] data = null;
            int dataLen = 0;

            // 获取当前配置的压缩算法实例（核心修改点2）
            CompressionStrategy compressor = compressionFactory.getCurrentStrategy();

            if (!transferReview) { // MongoDB中转模式
                // 使用工厂获取的算法进行压缩（替代原来的CompressUtils.compress）
                data = compressor.compress(conditionStr);
                dataLen = data.length;
                t2 = System.currentTimeMillis();

                id = mongoClient.insert(Constants.COLLECTION_COMPOSE_ANALYZE_REQUEST, data);
                t3 = System.currentTimeMillis();

                if (null == id) {
                    throw new Exception("mongo client insert failure,id can't be null");
                }

                if (data.length > 500) {
                    return Result.error("文件压缩后仍然过大");
                }

                result = desensitizationService.composeAnalyze(id);
            } else { // 直连传输模式
                transferClient.createPost("/test");
            }

            long t4 = System.currentTimeMillis();

            if (result != null || darResult != null) {
                long t5 = System.currentTimeMillis(), t6 = t5, t7 = t5;

                if (transferReview == null || !transferReview) { // MongoDB模式结果解析
                    retId = result.getMessage();
                    byte[] compress = mongoClient.getBytes(retId, Constants.COLLECTION_COMPOSE_ANALYZE_RESPONSE);
                    t5 = System.currentTimeMillis();

                    // 使用工厂获取的算法进行解压（替代原来的CompressUtils.uncompress）
                    String uncompress = compressor.uncompress(compress);
                    t6 = System.currentTimeMillis();

                    finalResult = JSONUtil.toBean(uncompress, String.class);
                    t7 = System.currentTimeMillis();
                } else { // 直连模式
                    finalResult = darResult.getMessage();
                }

                // 性能日志
                log.warn("识别统计：原大小={}|压缩大小={}|压缩时长={}|压缩比例={}%|入库时长={}|调用时长={}|出库时长={}|解压时长={}|反序列化时长={}|总时长={}",
                        conditionStr.getBytes().length,
                        dataLen,
                        (t2 - t1),
                        format(dataLen, conditionStr.getBytes().length),
                        (t3 - t2),
                        (t4 - t3),
                        (t5 - t4),
                        (t6 - t5),
                        (t7 - t6),
                        (t7 - t1)
                );

                return Result.success(finalResult);
            } else {
                log.error("数据脱敏识别异常，返回结果为空");
            }
        } catch (Exception e) {
            log.error("数据脱敏+识别异常", e);
        } finally {
            if (id != null) {
                mongoClient.delete(id, Constants.COLLECTION_COMPOSE_ANALYZE_REQUEST);
            }
            if (retId != null) {
                mongoClient.delete(retId, Constants.COLLECTION_COMPOSE_ANALYZE_RESPONSE);
            }
        }
        return Result.error("");
    }

    /*
     * 计算压缩节省百分比
     */
    private String format(int x, int y) {
        try {
            NumberFormat format = NumberFormat.getInstance();
            format.setMaximumFractionDigits(2);
            float a = (float) x;
            float b = (float) y;
            return format.format((b - a) / b * 100);
        } catch (Exception e) {
            log.error("计算压缩比例异常", e);
            return "N/A";
        }
    }
}
